#include "automata.h"
#include "testInputs.h"

#define NO_DEBUG

#ifdef DEBUG
    #define DEBUGM  printf
#else
    #define DEBUGM  //
#endif


void testInput(t_table * t)
{
     int i,j, result;
     void * aux;
     
     #ifdef DEBUG
        printf("Inputs: %d\n\n", t->input.dim);
        for (i = 0; i < t->input.dim; i++)
            printf("  Input chain %d: \"%s\".\n", i, t->input.chains[i]);
     #endif
     
     for(i=0;i<t->input.dim;i++)
     {
          result=validarInput(t,t->input.chains[i]);
          
          DEBUGM("chains[%d]: %p. string: %s\n", i, t->input.chains[i], t->input.chains[i]);
          
          DEBUGM("aux: %p. chains[%d]: %p. string: %s\n", aux, i, t->input.chains[i], t->input.chains[i]);


          //Reserves some space in case empty chain was entered
          if((aux=(char*)realloc(t->input.chains[i],4))==NULL)
             error(1,"Could not allocate memory. Shame on you.");
          else
             t->input.chains[i]=aux;

          DEBUGM("aux: %p. chains[%d]: %p. string: %s\n\n", aux, i,t->input.chains[i], t->input.chains[i]);

          //Replace input chain with result
          if (result)
             strcpy(t->input.chains[i],"SI");
          else
             strcpy(t->input.chains[i],"NO");   
        
          DEBUGM("salida (in)[i:%d][p:%p][%s] \n",i, t->input.chains[i], t->input.chains[i]);

     }

    DEBUGM("\n");
     for(i=0;i<t->input.dim;i++)
     {
          DEBUGM("salida (out)[i:%d][p:%p][%s] \n",i, t->input.chains[i], t->input.chains[i]);
     }

}

int validarInput(t_table * t,char * string)
{
    int state,j=0,col;
    
    state=t->iniState;    
    
    DEBUGM("ENTER validarInput\n");
    
    while (string[j])
    {
        DEBUGM("#");
        col=getSymIndex(t->alphabet,string[j]);
        DEBUGM("getSymIndex (%d) done\n", col);
        state=t->transitions.data[state][col];
        DEBUGM("matrix access (%d) done\n", state);
        if (state==-1)
        {
            DEBUGM("Estado trampa!!\n");
            return 0;
	    }
        
        j++;
    }


    DEBUGM("\nLEAVING validarInput\n");
    
    if (isFinalStInd(t, state))
       return 1;  
    
    return 0;    
}
